package com.kexilo.system.user.service;

import com.kexilo.core.common.annotation.DataScope;
import com.kexilo.core.common.constant.UserConstants;
import com.kexilo.core.common.core.domain.TreeSelect;
import com.kexilo.core.common.exception.ServiceException;
import com.kexilo.core.common.utils.SecurityUtils;
import com.kexilo.core.common.utils.StringUtils;
import com.kexilo.core.role.domain.SysRole;
import com.kexilo.core.shared.dto.TreeNodeDTO;
import com.kexilo.core.user.domain.SysDept;
import com.kexilo.core.user.domain.SysUser;
import com.kexilo.system.user.mapper.SysDeptMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 * 
 * @author Kexilo
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    
    private static final Logger log = LoggerFactory.getLogger(SysDeptServiceImpl.class);
    
    @Autowired
    private SysDeptMapper deptMapper;
    
    /**
     * 查询部门管理数据
     * 
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    @Cacheable(value = "dept:list", key = "#dept.deptId != null ? #dept.deptId : 'all'", 
               condition = "#dept != null")
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }
    
    /**
     * 根据角色ID查询部门树信息
     * 
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        SysRole role = new SysRole();
        role.setRoleId(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.getDeptCheckStrictly());
    }
    
    /**
     * 构建前端所需要树结构
     * 
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    @Cacheable(value = "dept:tree", key = "#depts.size() + '_' + #depts.hashCode()", 
               condition = "#depts != null && !#depts.isEmpty()")
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }
    
    /**
     * 构建前端所需要下拉树结构
     * 
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Object> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream()
                .map(this::convertDeptToTreeNode)
                .map(TreeSelect::new)
                .collect(Collectors.toList());
    }
    
    /**
     * 将部门实体转换为树形节点DTO
     * 
     * @param dept 部门实体
     * @return 树形节点DTO
     */
    private TreeNodeDTO convertDeptToTreeNode(SysDept dept) {
        TreeNodeDTO node = new TreeNodeDTO();
        node.setId(dept.getDeptId());
        node.setLabel(dept.getDeptName());
        node.setParentId(dept.getParentId() != null ? dept.getParentId() : 0L);
        
        // 递归转换子节点
        if (dept.getChildren() != null && !dept.getChildren().isEmpty()) {
            List<TreeNodeDTO> childNodes = dept.getChildren().stream()
                    .map(this::convertDeptToTreeNode)
                    .collect(Collectors.toList());
            node.setChildren(childNodes);
        }
        
        return node;
    }
    
    /**
     * 根据部门ID查询信息
     * 
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    @Cacheable(value = "dept:info", key = "#deptId", condition = "#deptId != null && #deptId > 0")
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }
    
    /**
     * 根据ID查询所有子部门（正常状态）
     * 
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    @Cacheable(value = "dept:children:count", key = "#deptId", 
               condition = "#deptId != null && #deptId > 0")
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }
    
    /**
     * 是否存在部门子节点
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }
    
    /**
     * 查询部门是否存在用户
     * 
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }
    
    /**
     * 校验部门名称是否唯一
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId(), deptId);
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return false; // NOT_UNIQUE
        }
        return true; // UNIQUE
    }
    
    /**
     * 校验部门是否有数据权限
     * 
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = this.selectDeptList(dept);
            if (StringUtils.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }
    
    /**
     * 新增保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"dept:tree", "dept:info", "dept:list", "dept:children:count"}, allEntries = true)
    public int insertDept(SysDept dept) {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insertDept(dept);
    }
    
    /**
     * 修改保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"dept:tree", "dept:info", "dept:list", "dept:children:count"}, allEntries = true)
    public int updateDept(SysDept dept) {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }
    
    /**
     * 修改该部门的父级部门状态
     * 
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        String[] deptIdStrings = StringUtils.split(ancestors, ",");
        Long[] deptIds = Arrays.stream(deptIdStrings)
                .map(Long::parseLong)
                .toArray(Long[]::new);
        deptMapper.updateDeptStatusNormal(deptIds);
    }
    
    /**
     * 修改子元素关系
     * 
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectDeptList(new SysDept() {{
            setParentId(deptId);
        }});
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }
    
    /**
     * 删除部门管理信息
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"dept:tree", "dept:info", "dept:list", "dept:children:count"}, allEntries = true)
    public int deleteDeptById(Long deptId) {
        return deptMapper.deleteDeptById(deptId);
    }
    
    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }
    
    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }
    
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }
}
